<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use fast\Http;
use think\Db;
use think\Log;

/**
 * 康复
 *
 * @icon fa fa-circle-o
 */
class Recovery extends Backend
{

    /**
     * Recovery模型对象
     * @var \app\admin\model\Recovery
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Recovery;

    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (!empty($_SERVER['REMOTE_ADDR'])) {
                // 获取REMOTE_ADDR这个服务器变量
                $ip = $_SERVER['REMOTE_ADDR'];
            }elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                // 判断是否有HTTP_CLIENT_IP这个请求头，存在优先使用
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                // 判断是否有HTTP_X_FORWARDED_FOR这个请求头，存在优先使用
                $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
            }  else {
                $ip = '';
            }
            $redis = new \think\cache\driver\Redis(['length' => 3]);
            $redis->set($ip.$this->auth->id."uid",$_GET['uid']);
            $list = $this->model
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        $params = $this->request->post('row/a');
        if ( $this->request->isPost()) {
            if($this->auth->id){
                if (!empty($_SERVER['REMOTE_ADDR'])) {
                        // 获取REMOTE_ADDR这个服务器变量
                    $ip = $_SERVER['REMOTE_ADDR'];
                }elseif (!empty($_SERVER['HTTP_CLIENT_IP'])) {
                    // 判断是否有HTTP_CLIENT_IP这个请求头，存在优先使用
                    $ip = $_SERVER['HTTP_CLIENT_IP'];
                } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                    // 判断是否有HTTP_X_FORWARDED_FOR这个请求头，存在优先使用
                    $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
                }  else {
                    $ip = '';
                }
                $redis = new \think\cache\driver\Redis(['length' => 3]);
                $uid = $redis->get($ip.$this->auth->id."uid");
                $params['uid'] = $uid;
                $params['ip'] = $ip;
                $params['createtime'] = time();
                $params['updatetime'] = time();
                $id = $this->model->insertGetId($params);
                $user_data = Db::name("user")->where(['id'=>$uid])->find();
                    if($user_data && $user_data['openid']){
                    $config = get_addon_config('third');

                    $appId = $config['wechat']['app_id'];
                    $appSecret = $config['wechat']['app_secret'];
                    $mp = Db::table('fa_wechartmp')->where('appid',$user_data['appid'])->find();
                    $tempid = 'eWLVgE4gpvw81fIUOYliUYbsCWdKIMD4q90xLyqCboo';
                    if($mp){
                        $appId = $mp['appid'];
                        $appSecret = $mp['appsecret'];
                        $tempid = $mp['jktempid'];
                    }
                    $redis = new \think\cache\driver\Redis(['length' => 3]);
                    $token = $redis->get('wechat_access_token');
                    if(!$token){
                        $url2 ='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
                        $user_info = Http::get($url2);
                        //echo $url2;
                        // var_dump($user_info);exit;
                        $user_info = json_decode($user_info, true);

                        $token = $user_info['access_token'];
                        $redis->set('wechat_access_token', $token, 7000);
                    }
                    $url2 ='https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appId.'&secret='.$appSecret;
                    $user_info = Http::get($url2);
                    //echo $url2;
                    // var_dump($user_info);exit;
                    $user_info = json_decode($user_info, true);

                    $token = $user_info['access_token'];


                    $auth_arr['template_id'] = $tempid;

                    $auth_arr['url'] = "https://jiankangapp.bigchun.com";
                    $auth_arr['touser'] = $user_data['openid'];
                    $product_data = Db::name("product")->where('id','in',$params['product_ids'])->select();
                    $product_str = '';
                    foreach ($product_data as $k=>$v){
                        $product_str .= $v['name'].',';
                    }
                    $auth_data['thing3']['value'] = mb_substr(trim($product_str,','), 0, 20);;
                    $auth_data['time5']['value'] = date('Y-m-d H:i:s',time());

                    $auth_arr['data'] = $auth_data;
                    $auth_arr['miniprogram_state'] = "trial";
                    $auth_arr['lang'] = "zh_CN";
                    $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$token;
                    $appid_data = \app\common\model\User::sendCurl(stripslashes($url), json_encode($auth_arr,true), 'post',
                        array('Content-Type:application/json'));

                    //echo json_encode($auth_arr)."__appid_data:".json_encode($appid_data);exit;
                    Log::write("康复fasong：".json_encode($auth_arr)."__appid_data:".json_encode($appid_data)."__url:".$url);
                }
                $this->success("添加成功");
            }else{
                $this->token();
            }

        }else{
            $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
            $this->view->assign("agency_id", $admin_data['agency_id']);
            $this->view->assign("admin_id", $this->auth->id);
            return parent::add();
        }
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        //echo $this->model->getLastSql();
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $admin_data = Db::name("admin")->where(['id'=>$this->auth->id])->find();
        $this->view->assign("agency_id", $admin_data['agency_id']);
        $this->view->assign("admin_id", $this->auth->id);
        return parent::edit($ids);
    }
}
